package com.yuhanxun.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.dfish.downloadtool.util.ProgressControl;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class DealHttp {
	public static String getXmlKeyValue(String request) {
		String ret = null;
		HttpResponse httpResponse = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpRequest = new HttpGet(request);
			httpResponse = httpClient.execute(httpRequest);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			ret = stream2String(httpResponse.getEntity().getContent());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}


	public static boolean isConnectInternet(Activity act) {
		ConnectivityManager conManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
		if (networkInfo != null) {
			return networkInfo.isAvailable();
		}
		return false;
	}

	private static String stream2String(InputStream inputStream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 1024); // 强制缓存大小为1M
		StringBuilder sb = new StringBuilder();

		String line = null;

		try {
			while ((line = reader.readLine()) != null) { // 处理换行符
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static synchronized boolean downloadFile(String pathURL, String pathFile, String md5) {
		int byteread = 0;
		try {
			URL url = new URL(pathURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			int fileLength = conn.getContentLength();
			// conn.setRequestMethod("GET"); //以GET方式连接
			// conn.setRequestProperty("Connection", "Keep-Alive"); //保持一直连接
			conn.setConnectTimeout(1000 * 5); // 连接超时5分钟
			// conn.setAllowUserInteraction(true);
			InputStream inStream = conn.getInputStream();

			String fileName = pathURL.substring(pathURL.lastIndexOf("/") + 1);
			String tempDir = AppGlobalVariable.getDIR_DOWNLOAD_TEMP();
			String tempFile = tempDir + fileName + ".temp";

			File oldTemp = new File(tempFile);
			if (oldTemp.exists())
				oldTemp.delete();
			FileOutputStream fs = new FileOutputStream(oldTemp);

			byte[] buffer = new byte[81920];
			int num = 0;
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
				num += byteread;
				System.out.println(tempFile + "--已下载--" + num / 1000 + "K" + "--" + num * 100 / fileLength + "%");
			}

			fs.close();
			conn.disconnect();

//			if (md5 != null) {
//				File file = new File(tempFile);
//				FileInputStream in = new FileInputStream(tempFile);
//				ByteArrayOutputStream out = new ByteArrayOutputStream((int) file.length());
//				byte[] cache = new byte[1048576];
//				for (int i = in.read(cache); i != -1; i = in.read(cache)) {
//					out.write(cache, 0, i);
//				}
//
//				String retmd5 = calcMD5(out.toByteArray());
//				retmd5.toUpperCase();
//				in.close();
//				out.close();
//
//				if (retmd5.equalsIgnoreCase(md5)) {
//					DealFile.recoverFile_move(pathFile, tempFile);
//					return true;
//				} else {
//					return false;
//				}
//
//			}
			DealFile.recoverFile_move(pathFile, tempFile);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	public static synchronized boolean downloadFile(String pathURL, String pathFile, String md5, ProgressControl ui) {
		int byteread = 0;
		try {
			URL url = new URL(pathURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			int fileLength = conn.getContentLength();
			// conn.setRequestMethod("GET"); //以GET方式连接
			// conn.setRequestProperty("Connection", "Keep-Alive"); //保持一直连接
			conn.setConnectTimeout(1000 * 5); // 连接超时5分钟
			// conn.setAllowUserInteraction(true);
			InputStream inStream = conn.getInputStream();

			String fileName = pathURL.substring(pathURL.lastIndexOf("/") + 1);
			String tempDir =AppGlobalVariable.getDIR_DOWNLOAD_TEMP();
			String tempFile = tempDir + fileName + ".temp";

			File oldTemp = new File(tempFile);
			if (oldTemp.exists())
				oldTemp.delete();
			FileOutputStream fs = new FileOutputStream(oldTemp);

			byte[] buffer = new byte[81920];
			int num = 0;
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
				num += byteread;
				System.out.println(pathFile + "--已下载--" + num / 1000 + "K" + "--" + num * 100 / fileLength + "%");
				ui.stepControl(num * 100 / fileLength);
			}

			fs.close();
			conn.disconnect();

//			if (md5 != null) {
//				// long start = System.currentTimeMillis();
//				File file = new File(tempFile);
//				FileInputStream in = new FileInputStream(tempFile);
//				ByteArrayOutputStream out = new ByteArrayOutputStream((int) file.length());
//				byte[] cache = new byte[1048576];
//				for (int i = in.read(cache); i != -1; i = in.read(cache)) {
//					out.write(cache, 0, i);
//				}
//
//				String retmd5 = calcMD5(out.toByteArray());
//				retmd5.toUpperCase();
//				// System.out.println("----------------md5---"+retmd5+"---------------------"+(System.currentTimeMillis()-start));
//				in.close();
//				out.close();
//
//				if (retmd5.equalsIgnoreCase(md5)) {
//					DealFile.recoverFile_move(pathFile, tempFile);
//					return true;
//				} else {
//					return false;
//				}
//
//			}
			DealFile.recoverFile_move(pathFile, tempFile);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
}
